// pages/book/book.js
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    nodes: [  
      { name: 'p', children: [{ text: '原价：', style: { color: 'red' } }, { text: '¥100', style: { color: 'red' } }] },  
      { name: 'line', style: { height: '1px', backgroundColor: 'black', marginLeft: '5px' } },  
      { name: 'p', children: [{ text: '现价：', style: { color: 'green' } }, { text: '¥80', style: { color: 'green' } }] }  
    ]  ,
    bannerList: [  
    ]  ,//轮播图
    addressList:null,
    giftCount:null,//赠品数量
    orderGiftDesc:"",//赠品商品描述
    deliveryRange:null, //配送范围 比如坪地场乡内
    index:null,//收货人地址选中的index 值
    number:'',
    prepaymentAmount:0,
    orderType:1, //0 预约订单   
    takeType:4,//4上门自取  2送货上门
    orderInfo:{},
    shopInfo:{}, //店铺信息
    consigneeInfo:{
      receiverAddress:'',
      receiverMobile:'',
      receiver:''
    }, //收货人信息
    paymentType:"routine",
    from:"routine",
    goods:[
      {
        spuId:1,
        specType:0,
        spuSellPrice:20,
        spuTitle:"订制豆腐果",
        number:0
      }
    ],
    totalPayPrice:0,
    realPayPrice:0,
    remark:"预约订单",
    pre_max_book_num:50,//最大预定数量
    fullPreBookPrice:20,//原始价格
    partPreBookPrice:20,
    secondPreBookPrice:18,
    threePreBookPrice:15,
    minPreBookPrice:15,
    pre_percentage:0.5 //预付百分比
  },
  onRadioChangeWay(e){
    this.setData({ takeType:e.detail.value });
    console.log(this.data.takeType)
  },
  onRadioChange(e) {  
    let type = e.detail.value; // 获取选中的选项值  
    console.log("onRadioChange"+type)
    this.getpriceByType(type)
    this.setData({ orderType: type }); // 更新数据，将选中的选项值赋给selectedType属性  
    // 在这里可以添加选中选项后的逻辑处理，例如发送请求到服务器等操作  
  },
  bindPickerChange: function(e) {
    let index = e.detail.value
    console.log('picker发送选择改变，携带值为', index)
    this.setData({
      index: index,
      'consigneeInfo.receiver':this.data.addressList[index].fullname,
      'consigneeInfo.receiverAddress':this.data.addressList[index].address,
      'consigneeInfo.receiverMobile':this.data.addressList[index].userPhone
    })
  },
  getDictList(){
    app.wxRequest('GET', '/dictDetail/getDictList', this.data, (res) => {
      if (200 == res.code) {
        this.setData({
          fullPreBookPrice:parseInt(res.data.full_pre_price),
          partPreBookPrice:parseInt(res.data.part_pre_price),
          pre_percentage:res.data.pre_percentage,
          pre_max_book_num:parseInt(res.data.pre_max_book_num),
          pre_mode:res.data.pre_mode
        })

      }else{
        app.showMsg(res.msg);
      }
    }, (err) => {
        app.showMsg(err.errMsg);
    })
  },
  getaddressList(){
    app.wxRequest('GET', '/userAddress/getList', null, (res) => {
      if (200 == res.code) {
        this.setData({
          addressList:res.data
        })
      }else{
        app.showMsg(res.msg);
      }
    }, (err) => {
        app.showMsg(err.errMsg);
    })
  },
  getpriceByType(type){
   const number = this.data.number
   console.log("number"+number)
   if(!number>0){
    return;
  }
  //则是按照赠送规则模式
  let allUnitPrice =this.data.fullPreBookPrice;
  let giftCount; //赠送的数量
  if(pre_mode="gift"){
    if(number>=5){
      giftCount = this.calculateGiftCount(number);
   }
  }else if(pre_mode="quantity"){
    //按照数量来计算价格
     allUnitPrice=this.calculateAmount(number);
  }
   console.log("当前单价="+allUnitPrice)
   const percentage = this.data.pre_percentage;
   const partUnitPrice =this.data.partPreBookPrice;
  // const partUnitPrice =1;
   let price=0;
   let totalPrice = 0
   if(type==1){
      price= allUnitPrice*number
      totalPrice = price
   }else if(type==0){
    totalPrice=partUnitPrice*number
     price= totalPrice*percentage
   }else{
     app.showMsg("类型异常");
     return
   }
   console.log(price)
   console.log(totalPrice)
     this.setData({
       prepaymentAmount:price,
       totalPayPrice:totalPrice,
       realPayPrice:price
     })

  },
  inputChange(event){
    const type= this.data.orderType
    let num =event.detail.value
    if(num=="" || num <5 ){
      console.log("num==null")
      this.setData({
        giftCount : null
      })
    }
    if(type==null){
      app.showMsg("请选择你要预约的方式");
      return
    }
    console.log("num=="+num)
    console.log("this.data.pre_max_book_num"+this.data.pre_max_book_num)
    console.log(num>=this.data.pre_max_book_num)
    if(num>this.data.pre_max_book_num){
      this.setData({
        number:'',
        totalPayPrice:0,
        prepaymentAmount:0
      })
      app.showMsg("你预约的数量过大，联系商家,最大预约数量为"+this.data.pre_max_book_num+"斤");
      return;
    }
    console.log(num)
    //则是按照赠送规则模式
    let allUnitPrice =this.data.fullPreBookPrice;
    let giftCount = null;
    let orderGiftDesc ="";
    if(pre_mode="gift"){
      if(num>=5){
        giftCount = this.calculateGiftCount(num);
        orderGiftDesc = "赠品："+giftCount+"斤";
     }
    }else if(pre_mode="quantity"){
      //按照数量来计算价格
       allUnitPrice=this.calculateAmount(num);
    }
   // const allUnitPrice=this.data.fullPreBookPrice;
   //计算单价 现在不按单价计算了 
    
   console.log("当前单价="+allUnitPrice)
    const partUnitPrice =this.data.partPreBookPrice;
    const percentage = this.data.pre_percentage;
    let price=0;
    let totalPrice = 0
    console.log("percentage="+percentage)
    console.log("type="+type)
   if(type==1){
      price= allUnitPrice*num
      totalPrice = price
   }else if(type==0){
      totalPrice=partUnitPrice*num
      price = totalPrice*percentage
   }else{
     app.showMsg("类型异常");
     return
   }
   
     this.setData({
       number:num,
       prepaymentAmount:price,
       totalPayPrice:totalPrice,
       realPayPrice:price,
       orderGiftDesc:orderGiftDesc,
       giftCount
     })
  },
  // 假设传入的单位数量为 unitCount
  calculateAmount(unitCount) {
    if (unitCount <= 10) {
      // 单位数量小于等于10时，可根据具体需求设置默认金额，这里先假设为某个值，你可以修改
      return this.data.fullPreBookPrice; 
    } else if(unitCount >10 && unitCount <=15){
      return this.data.secondPreBookPrice; 
    }else if(unitCount >15 && unitCount <20){
      let amount = 19;
      const diff = unitCount - 16;
      amount -= diff;
      return Math.max(amount, 16);
    }else{
      return this.data.minPreBookPrice;
    }
  },
  // 假设传入的单位数量为 unitCount
  calculateGiftCount(unitCount) {
    //返回的数据是赠送的数量
    if(unitCount >=5 && unitCount <10){
      return 0.5; 
    } 
    else if(unitCount >=10 && unitCount <20){
      return 1; 
    } else if(unitCount >=20 && unitCount <30){
      return 3; 
    }else if(unitCount >=30 && unitCount <40){
      return 5; 
    }else if(unitCount >=40 && unitCount <50){
      return 7; 
    }else if(unitCount >=50){
      return 11;
    }
  },
  goPrepayment(){
    if(!app.globalData.userToken){
      app.showMsg("请先登录")
      setTimeout(()=>{
        wx.switchTab({
          url: '/pages/me/me',
        })
      },1000);
      return;
    }
    console.log("goPrepayment")
    if(this.data.takeType!=4 && this.data.takeType!=2){
      app.showMsg("请选择取货方式");
      return;
    }
    if(this.data.number<=0){
      app.showMsg("请输入预定数量");
      return;
    }
   const mobile= this.data.consigneeInfo.receiverMobile
    if(mobile==""){
      app.showMsg("收货地址不能为空");
      return 
    }
    if(mobile.length!=11){
      app.showMsg("联系方式格式不对");
      return 
    }
    const receiver= this.data.consigneeInfo.receiver
    if(receiver==""){
      app.showMsg("联系人姓名不能为空");
      return 
    }
    const address= this.data.consigneeInfo.receiverAddress
    if(this.data.takeType==2 && address==""){
      app.showMsg("收获地址不能为空");
      return 
    }
    this.data.goods[0].number=this.data.number;
    app.wxRequest('POST', '/order/create', this.data, (res) => {
      if (200 == res.code) {
        console.log("订单预定创建成功")
        if('WECHAT_PAY'===res.data.status){
          this.initiatePayment(res.data.result.jsConfig)
        }
      }else{
        app.showMsg(res.msg);
      }
    }, (err) => {
        app.showMsg(err.errMsg);
    })
    
  },
  initiatePayment(data){
    console.log(data)
    wx.requestPayment({
      timeStamp: data.timeStamp,
      nonceStr: data.nonceStr,
      package: data.package,
      signType: 'MD5',
      paySign: data.paySign,
      success: res => {
        this.setData({
          payResult: '支付成功'
        });
        wx.switchTab({
          url: '/pages/order/order'
        }) 
      },
      fail: error => {
        wx.showToast({
          title: '用户取消支付',
          icon: 'error',
          duration: 1000
        })
        setTimeout(()=>{
          wx.switchTab({
            url: '/pages/order/order'
          }) 
        },1000)
        
      }
    });
  },
  bindblurMobile(e){
    const mobile = e.detail.value;
    console.log(mobile);
    this.setData({
     'consigneeInfo.receiverMobile':mobile
    })
  },
  bindblurReceiver(e){
    const receiver = e.detail.value;
    console.log(receiver)
    this.setData({
      'consigneeInfo.receiver':receiver
     })
  },
  bindblurAddress(e){
    const address = e.detail.value;
    console.log(address)
    this.setData({
      'consigneeInfo.receiverAddress':address
     })
    console.log(address)
  },
  getBannerData(){
    app.wxRequest('GET', '/banner/getList', null, (res) => {
      if (200 == res.code) {
        this.setData({
          bannerList:res.data
        })
      }else{
        app.showMsg(res.msg);
      }
    }, (err) => {
        app.showMsg(err.errMsg);
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    console.log("onLoad")
    this.getBannerData();
    this.getDictList();
    this.getaddressList()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    console.log("onReady")
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.getaddressList();
    this.getDictList();
    console.log("onShow")
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})